package com.fly.caihong.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fly.caihong.R;
import com.fly.caihong.adapter.ImageAddAdapter;
import com.fly.caihong.base.BaseActivity;
import com.fly.caihong.listener.LastItemUnDragAndSwipeCallback;
import com.fly.caihong.utils.ItemSpacesDecoration;
import com.fly.caihong.utils.ScreenUtils;
import com.fly.caihong.utils.SizeUtils;
import com.fly.caihong.utils.StatusBarUtils;
import com.fly.caihong.utils.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class FeedbackActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    public static final String IMAGE_ADD = "image/add";
    private RecyclerView mRecyclerView;
    private BaseItemDraggableAdapter mImageAdapter;
    private EditText mEditText;
    private List<String> mImagePaths = new ArrayList<>();
    private String mCurrentPhotoPath;
    private int mCompressCount, mCompressPosition;

    @Override
    protected int getLayout() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initViews() {
        super.initViews();
        StatusBarUtils.setColor(this, ActivityCompat.getColor(this, R.color.theme_bg), 0);
        mEditText = findViewById(R.id.edt_content);
        mImagePaths.add(IMAGE_ADD);
        mRecyclerView = findViewById(R.id.rv_grid);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.addItemDecoration(new ItemSpacesDecoration(5, 5, 5, 5));
        mRecyclerView.setHasFixedSize(true);
        mImageAdapter = new ImageAddAdapter(mImagePaths, (ScreenUtils.getScreenWidth() - SizeUtils.dp2px(30)) / 3);
        mRecyclerView.setAdapter(mImageAdapter);
        mImageAdapter.enableDragItem(new LastItemUnDragAndSwipeCallback(mRecyclerView, mImageAdapter).getItemTouchHelper());
        mImageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == mImagePaths.size() - 1) {
                    if (EasyPermissions.hasPermissions(FeedbackActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE
                            , Manifest.permission.CAMERA)) {
                        launchAlbum();
                    } else {
                        EasyPermissions.requestPermissions(FeedbackActivity.this, getString(R.string.permission_extra_storage_hint)
                                , 190, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
                    }
                }
            }
        });
    }

    @Override
    protected void setStatusBarStyle() {
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.tv_publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditText.getText().toString().trim().equals("")) {
                    ToastUtils.showLong(mEditText.getHint());
                    return;
                }
                showLoading("正在提交数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showLong("提交成功");
                        finish();
                    }
                }, 2000);
            }
        });
    }

    /**
     * 准备加载相册
     */
    private void launchAlbum() {
        if (mImagePaths.size() >= 3 + 1) {
            ToastUtils.showLong("不能超过3张");
            return;
        }
        int size = ScreenUtils.getScreenWidth() / 3 - SizeUtils.dp2px(10);
        int pSize = mImagePaths.size();
        Matisse.from(this)
                .choose(MimeType.ofImage())//只显示照片
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, getPackageName() + ".fileprovider"))
                .countable(false)//无序选择图片
                .maxSelectable(pSize == 0 ? 3 : 3 - pSize + 1)//最大选择数量为3
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(101);//请求码
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param images
     */
    private void compressImages(List<String> images) {
        mCompressCount = images.size();
        mCompressPosition = 0;
        Luban.with(this)
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        mCompressPosition++;
                        mImagePaths.add(0, file.getPath());
                        mImageAdapter.notifyItemInserted(0);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                List<String> retList = Arrays.asList(mCurrentPhotoPath);
                Collections.reverse(retList);
                compressImages(retList);
            } else if (requestCode == 101) {
                if (!mImagePaths.contains(IMAGE_ADD)) {
                    mImagePaths.add(IMAGE_ADD);
                }
                compressImages(Matisse.obtainPathResult(data));
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == 190) {
            launchAlbum();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

}
